<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1400px">
    <!-- 基础信息部分 -->
    <div class="form-section">
      <div class="section-title">基础信息</div>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        v-loading="formLoading"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户类型:" prop="customerType">
              <el-radio-group v-model="formData.customerType">
                <el-radio label="enterprise">企业客户</el-radio>
                <el-radio label="personal">个人客户</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 个人客户表单 -->
        <template v-if="formData.customerType === 'personal'">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="客户名称:" prop="personName">
                <el-input v-model="formData.personName" placeholder="请输入客户名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="助记名称:" prop="personMnemonicWord">
                <el-input v-model="formData.personMnemonicWord" placeholder="请输入助记名称" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性别:" prop="personSex">
                <el-radio-group v-model="formData.personSex">
                  <el-radio label="1">男</el-radio>
                  <el-radio label="2">女</el-radio>
                  <el-radio label="3">未知</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电子邮箱:" prop="personEmail">
                <el-input v-model="formData.personEmail" placeholder="请输入电子邮箱" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="座机:" prop="personLandline">
                <el-input v-model="formData.personLandline" placeholder="请输入座机" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="移动电话:" prop="personPhone">
                <el-input v-model="formData.personPhone" placeholder="请输入移动电话" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="Facebook:" prop="personFacebook">
                <el-input v-model="formData.personFacebook" placeholder="请输入Facebook" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="ins:" prop="personIns">
                <el-input v-model="formData.personIns" placeholder="请输入ins" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="TikTok:" prop="personTiktok">
                <el-input v-model="formData.personTiktok" placeholder="请输入TikTok" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Youtube:" prop="personYoutube">
                <el-input v-model="formData.personYoutube" placeholder="请输入Youtube" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="Linkedin:" prop="personLinkedin">
                <el-input v-model="formData.personLinkedin" placeholder="请输入Linkedin" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮编:" prop="personPostalCode">
                <el-input v-model="formData.personPostalCode" placeholder="请输入邮编" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="国家地区:" prop="country">
                <el-input v-model="formData.country" placeholder="请输入国家地区" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所在时区:" prop="timeZone">
                <el-input v-model="formData.timeZone" placeholder="请输入所在时区" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所在城市:" prop="city">
                <el-input v-model="formData.city" placeholder="请输入所在城市" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="港口:" prop="harbor">
                <el-input v-model="formData.harbor" placeholder="请输入港口" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="常住地址:" prop="addressPermanent">
                <el-input v-model="formData.addressPermanent" placeholder="请输入常住地址" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="邮寄地址:" prop="addressMail">
                <el-input v-model="formData.addressMail" placeholder="请输入邮寄地址" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        
        <!-- 企业客户表单 -->
        <template v-else>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="公司名称:" prop="companyName" required>
                <el-input v-model="formData.companyName" placeholder="请输入公司名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="公司简称:" prop="companyAbbrevia">
                <el-input v-model="formData.companyAbbrevia" placeholder="请输入公司简称" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="经营范围:" prop="companyRange">
                <el-input v-model="formData.companyRange" placeholder="请输入经营范围" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="公司规模:" prop="companyScale">
                <el-input v-model="formData.companyScale" placeholder="请输入公司规模" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="公司邮编:" prop="companyPostal">
                <el-input v-model="formData.companyPostal" placeholder="请输入公司邮编" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="公司电话:" prop="companyPhone">
                <el-input v-model="formData.companyPhone" placeholder="请输入公司电话" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="公司传真:" prop="companyFax">
                <el-input v-model="formData.companyFax" placeholder="请输入公司传真" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="公司网站:" prop="companyWebsite">
                <el-input v-model="formData.companyWebsite" placeholder="请输入公司网站" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="国家地区:" prop="country">
                <el-input v-model="formData.country" placeholder="请输入国家地区" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所在时区:" prop="timeZone">
                <el-input v-model="formData.timeZone" placeholder="请输入所在时区" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所在城市:" prop="city">
                <el-input v-model="formData.city" placeholder="请输入所在城市" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="港口:" prop="harbor">
                <el-input v-model="formData.harbor" placeholder="请输入港口" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="公司地址:" prop="addressPermanent">
                <el-input v-model="formData.addressPermanent" placeholder="请输入公司地址" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="邮寄地址:" prop="addressMail">
                <el-input v-model="formData.addressMail" placeholder="请输入邮寄地址" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注:" prop="remark">
              <el-input 
                v-model="formData.remark" 
                placeholder="请输入备注" 
                type="textarea"
                :rows="2"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    
    <!-- 分类信息部分 -->
    <div class="form-section">
      <div class="section-title">分类信息</div>
      <el-form :model="formData" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户来源" prop="sourceCode">
              <el-select 
                v-model="formData.sourceCode" 
                placeholder="请选择客户来源"
                style="width: 100%"
              >
               <el-option
                v-for="item in props.sourceCodes"
                :key="item"
                :label="item"
                :value="item"
              />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行业分类:" prop="industryCode">
              <el-select 
                v-model="formData.industryCode" 
                placeholder="请选择行业分类"
                style="width: 100%"
              >
                <el-option
                v-for="item in props.industryCodes"
                :key="item"
                :label="item"
                :value="item"
              />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户优先级:" prop="priorityCode">
              <el-select 
                v-model="formData.priorityCode" 
                placeholder="请选择客户优先级"
                style="width: 100%"
              >
                <el-option
                v-for="item in props.priorityCodes"
                :key="item"
                :label="item"
                :value="item"
              />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户星级:" prop="starCode">
              <el-select 
                v-model="formData.starCode" 
                placeholder="请选择客户星级"
                style="width: 100%"
              >
                <el-option
                v-for="item in props.starCodes"
                :key="item"
                :label="item"
                :value="item"
              />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户阶段:" prop="stageCode">
              <el-select 
                v-model="formData.stageCode" 
                placeholder="请选择客户阶段"
                style="width: 100%"
              >
                <el-option
                v-for="item in props.stageCodes"
                :key="item"
                :label="item"
                :value="item"
              />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户状态:" prop="statusCode">
              <el-select 
                v-model="formData.statusCode" 
                placeholder="请选择客户状态"
                style="width: 100%"
              >
                <el-option
                v-for="item in props.statusCodes"
                :key="item"
                :label="item"
                :value="item"
              />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    
    <!-- 联系人部分 -->
    <div class="form-section">
      <div class="section-title">
        联系人
        <el-row>
        <div style="float: left; margin-top: 10px;">
          <el-button type="primary"  @click="openContactForm('create')">新增</el-button>
          <el-button 
            style="
              background-color: transparent;
              border: 1px solid #409eff;
              color: #409eff;
            "
            type="primary"
            plain
            :disabled="selectedContactIds.length !== 1" 
            @click="openContactForm('update', selectedContactIds[0])"
          >
            编辑
          </el-button>
          <el-button 
            style="
              background-color: transparent;
              border: 1px solid #409eff;
              color: #409eff;
            "
            type="primary"
            plain
            :disabled="selectedContactIds.length === 0" 
            @click="batchDeleteLocalContacts"
          >
            删除
          </el-button>
        </div>
        </el-row>
      </div>
      
      <el-table 
        :data="localContacts" 
        border 
        style="width: 100%"
        @selection-change="handleContactSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="联系人" width="80" align="center"/>
        <el-table-column prop="sex" label="性别" width="60" align="center">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.sex" />
          </template>
        </el-table-column>
        <el-table-column prop="position" label="职务" width="120" align="center"/>
        <el-table-column prop="email" label="邮箱" width="150" align="center"/>
        <el-table-column prop="landline" label="座机" width="120" align="center"/>
        <el-table-column prop="phone" label="移动电话" width="120" align="center"/>
        <el-table-column prop="facebook" label="Facebook" width="120" align="center"/>
        <el-table-column prop="ins" label="ins" width="120" align="center"/>
        <el-table-column prop="tiktok" label="TIKTOK" width="120" align="center"/>
        <el-table-column prop="youtube" label="Youtube" width="120" align="center"/>
        <el-table-column prop="linkedin" label="Linkedin" width="120" align="center"/>
        <el-table-column prop="remark" label="备注" width="120" align="center"/>
        
        
      </el-table>
    </div>
    
    <template #footer>
      <div style="display: flex; justify-content: center; gap: 16px;">
        <el-button @click="dialogVisible = false" size="large" style="width: 100px;">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="formLoading" size="large" style="width: 100px;">保 存</el-button>
      </div>
    </template>
  </Dialog>

  <!-- 联系人表单弹窗 -->
  <Dialog :title="contactDialogTitle" v-model="contactDialogVisible" width="800px">
    <el-form 
      ref="contactFormRef" 
      :model="contactFormData" 
      :rules="contactFormRules" 
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="contactFormData.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别:" prop="sex">
                <el-radio-group v-model="formData.personSex">
                  <el-radio label="1">男</el-radio>
                  <el-radio label="2">女</el-radio>
                  <el-radio label="3">未知</el-radio>
                </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职务" prop="position">
            <el-input v-model="contactFormData.position" placeholder="请输入职务" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="contactFormData.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="座机" prop="landline">
            <el-input v-model="contactFormData.landline" placeholder="请输入座机" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="移动电话" prop="phone">
            <el-input v-model="contactFormData.phone" placeholder="请输入移动电话" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="Facebook" prop="facebook">
            <el-input v-model="contactFormData.facebook" placeholder="请输入Facebook" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="ins" prop="ins">
            <el-input v-model="contactFormData.ins" placeholder="请输入ins" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="TikTok" prop="tiktok">
            <el-input v-model="contactFormData.tiktok" placeholder="请输入TikTok" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Youtube" prop="youtube">
            <el-input v-model="contactFormData.youtube" placeholder="请输入Youtube" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="Linkedin" prop="linkedin">
            <el-input v-model="contactFormData.linkedin" placeholder="请输入Linkedin" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="contactFormData.remark" placeholder="请输入备注" type="textarea" :rows="2" />
          </el-form-item>
        </el-col>
      </el-row>
      
    </el-form>
    
    <template #footer>
      <el-button @click="contactDialogVisible = false" width="100px">取 消</el-button>
      <el-button type="primary" @click="saveLocalContact" style="margin-right: 100px;" width="100px">保 存</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { CustInfoApi, CustInfoVO } from '@/api/customermanager/custmanage'
import { CustContactsApi, CustContactsVO } from '@/api/customermanager/custcontacts'
import { number } from 'vue-types'
import { error } from 'console'

/** 客户信息 表单 */
defineOptions({ name: 'CustInfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

// 联系人相关状态
const contactDialogVisible = ref(false) // 联系人弹窗是否展示
const contactDialogTitle = ref('') // 联系人弹窗标题
const contactFormRef = ref() // 联系人表单 Ref
const contactFormType = ref('') // 联系人表单类型
const localContacts = ref<Array<CustContactsVO & { localId: string }>>([]) // 本地暂存的联系人列表
const selectedContactIds = ref<string[]>([]) // 选中的联系人本地ID数组
let localContactIdCounter = 0 // 本地联系人ID计数器

watch(dialogVisible, (visible) => {
  if (visible) {
    // 弹窗显示后添加边界检查
    setTimeout(() => {
      const dialog = document.querySelector('.el-dialog')
      if (dialog) {
        const observer = new MutationObserver(() => {
          const rect = dialog.getBoundingClientRect()
          if (rect.top < 10) {
            dialog.style.top = '10px'
            dialog.style.transform = 'none'
          }
        })
        observer.observe(dialog, { attributes: true, attributeFilter: ['style'] })
      }
    }, 100)
  }
})

const contactFormData = ref<CustContactsVO & { localId?: string }>({
  localId: undefined,
  id: undefined,
  custId: undefined,
  name: undefined,
  sex: undefined,
  position: undefined,
  email: undefined,
  landline: undefined,
  phone: undefined,
  socialAcc: undefined,
  facebook: undefined,
  ins: undefined,
  tiktok: undefined,
  youtube: undefined,
  linkedin: undefined,
  remark: undefined
})

// 客户表单数据
const formData = ref({
  id: undefined,
  customerType: 'enterprise', // 默认为企业客户
  code: undefined,
  personName: undefined,
  personMnemonicWord: undefined,
  personSex: undefined,
  personEmail: undefined,
  personLandline: undefined,
  personPhone: undefined,
  personFacebook: undefined,
  personIns: undefined,
  personTiktok: undefined,
  personYoutube: undefined,
  personLinkedin: undefined,
  personPostalCode: undefined,
  companyName: undefined,
  companyAbbrevia: undefined,
  companyRange: undefined,
  companyScale: undefined,
  companyPostal: undefined,
  companyPhone: undefined,
  companyFax: undefined,
  companyWebsite: undefined,
  country: undefined,
  timeZone: undefined,
  city: undefined,
  harbor: undefined,
  addressPermanent: undefined,
  addressMail: undefined,
  sourceCode: undefined,
  industryCode: undefined,
  priorityCode: undefined,
  starCode: undefined,
  stageCode: undefined,
  statusCode: undefined,
  remark: undefined,
  listCustContactsSaveReqVO: [] // 新增联系人数组字段
})

// 表单验证规则
const formRules = reactive({
  companyName: [{ required: true, message: '公司名称不能为空', trigger: 'blur' }],
  personName: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }],
  personSex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  personPhone: [{ required: true, message: '移动电话不能为空', trigger: 'blur' }],
})

// 联系人表单验证规则
const contactFormRules = reactive({
  name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  phone: [{ required: true, message: '移动电话不能为空', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }]
})

const formRef = ref() // 表单 Ref

const props = defineProps<{
  stageCodes: string[]
  starCodes: string[]
  industryCodes: string[]
  statusCodes: string[]
  sourceCodes: string[]
  priorityCodes: string[]
}>()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CustInfoApi.getCustInfo(id)
      // 如果是修改模式，加载已有联系人
      if (formType.value === 'update') {
        await loadContacts()
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 加载联系人列表 */
const loadContacts = async () => {
  if (!formData.value.id) return
  
  try {
    const response = await CustContactsApi.getCustContactsPage({
      custId: formData.value.id,
      pageNo: 1,
      pageSize: 100
    })
    // 将已有联系人转为本地联系人格式
    localContacts.value = response.list.map(item => ({
      ...item,
      localId: `server_${item.id}` // 标记为服务器已有数据
    }))
  } catch (error) {
    console.error('加载联系人失败:', error)
  }
}

/** 处理表格选择项变化 */
const handleContactSelectionChange = (val: Array<CustContactsVO & { localId: string }>) => {
  selectedContactIds.value = val.map(item => item.localId)
}

/** 打开联系人表单弹窗 */
const openContactForm = (type: string, localId?: string) => {
  contactDialogVisible.value = true
  contactDialogTitle.value = type === 'create' ? '新增联系人' : '编辑联系人'
  contactFormType.value = type
  
  if (type === 'create') {
    contactFormData.value = {
      localId: undefined,
      id: undefined,
      custId: formData.value.id,
      name: undefined,
      sex: undefined,
      position: undefined,
      email: undefined,
      landline: undefined,
      phone: undefined,
      socialAcc: undefined,
      facebook: undefined,
      ins: undefined,
      tiktok: undefined,
      youtube: undefined,
      linkedin: undefined,
      remark: undefined
    }
  } else if (localId) {
    const contact = localContacts.value.find(item => item.localId === localId)
    if (contact) {
      contactFormData.value = { ...contact }
    }
  }
}

/** 保存本地联系人 */
const saveLocalContact = async () => {
  await contactFormRef.value.validate()
  
  const contactData = { ...contactFormData.value }
  
  if (contactFormType.value === 'create') {
    // 新增联系人，生成本地ID
    localContactIdCounter++
    contactData.localId = `local_${localContactIdCounter}`
    localContacts.value.push(contactData)
  } else {
    // 更新联系人
    const index = localContacts.value.findIndex(item => item.localId === contactData.localId)
    if (index !== -1) {
      localContacts.value.splice(index, 1, contactData)
    }
  }
  
  contactDialogVisible.value = false
  message.success('联系人已暂存')
}

/** 删除本地联系人 */
const deleteLocalContact = (localId: string) => {
  const index = localContacts.value.findIndex(item => item.localId === localId)
  if (index !== -1) {
    localContacts.value.splice(index, 1)
    message.success('联系人已删除')
  }
}

/** 批量删除本地联系人 */
const batchDeleteLocalContacts = () => {
  if (selectedContactIds.value.length === 0) {
    message.warning('请至少选择一条联系人记录')
    return
  }
  
  localContacts.value = localContacts.value.filter(
    item => !selectedContactIds.value.includes(item.localId)
  )
  selectedContactIds.value = []
  message.success(`已删除 ${selectedContactIds.value.length} 条联系人记录`)
}

/** 准备联系人数据 */
const prepareContactsData = () => {
  // 筛选出需要新增的联系人（本地新增的）
  const contactsToCreate = localContacts.value
    .filter(item => item.localId?.startsWith('local_'))
    .map(({ localId, ...rest }) => rest)
  
  // 如果是更新模式，筛选出需要更新的联系人（服务器已有但修改过的）
  const contactsToUpdate = formType.value === 'update' 
    ? localContacts.value
        .filter(item => item.localId?.startsWith('server_') && item.id)
        .map(({ localId, ...rest }) => rest)
    : []
  
  return [...contactsToCreate, ...contactsToUpdate]
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  
  // 准备联系人数据
  formData.value.listCustContactsSaveReqVO = prepareContactsData()
  
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CustInfoVO
    let statusCode=undefined
    
    if (formType.value === 'create') {
      // 新增客户（包含联系人）
      statusCode=await CustInfoApi.createCustInfo(data)
      if (statusCode < 0) {
        if(statusCode == -1)  throw new Error("该客户信息与系统现有客户【客户名称】重复！请重新编辑后再试")  
        if(statusCode == -2)  throw new Error("该客户信息与系统现有客户【国家地区】重复！请重新编辑后再试") 
        if(statusCode == -3)  throw new Error("该客户信息与系统现有客户【客户类型】重复！请重新编辑后再试")     
        if(statusCode == -4)  throw new Error("该客户信息与系统现有客户【电子邮箱】重复！请重新编辑后再试")     
        if(statusCode == -5)  throw new Error("该客户信息与系统现有客户【邮寄地址】重复！请重新编辑后再试") 
        if(statusCode == -6)  throw new Error("该客户信息【联系人】重复！请重新编辑后再试")
     }
      message.success(t('common.createSuccess'))
    } else {
      // 更新客户（包含联系人）
      statusCode=await CustInfoApi.updateCustInfo(data)
      if (statusCode < 0) {
        if(statusCode == -1)  throw new Error("该客户信息与系统现有客户【客户名称】重复！请重新编辑后再试")  
        if(statusCode == -2)  throw new Error("该客户信息与系统现有客户【国家地区】重复！请重新编辑后再试") 
        if(statusCode == -3)  throw new Error("该客户信息与系统现有客户【客户类型】重复！请重新编辑后再试")     
        if(statusCode == -4)  throw new Error("该客户信息与系统现有客户【电子邮箱】重复！请重新编辑后再试")     
        if(statusCode == -5)  throw new Error("该客户信息与系统现有客户【邮寄地址】重复！请重新编辑后再试") 
        if(statusCode == -6)  throw new Error("该客户信息【联系人】重复！请重新编辑后再试")
     }
      message.success(t('common.updateSuccess'))
    }
    //alert(statusCode)
    
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } catch (error) {

    message.error(error.message)
    console.error('保存失败:', error)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    customerType: 'enterprise',
    code: undefined,
    personName: undefined,
    personMnemonicWord: undefined,
    personSex: undefined,
    personEmail: undefined,
    personLandline: undefined,
    personPhone: undefined,
    personFacebook: undefined,
    personIns: undefined,
    personTiktok: undefined,
    personYoutube: undefined,
    personLinkedin: undefined,
    personPostalCode: undefined,
    companyName: undefined,
    companyAbbrevia: undefined,
    companyRange: undefined,
    companyScale: undefined,
    companyPostal: undefined,
    companyPhone: undefined,
    companyFax: undefined,
    companyWebsite: undefined,
    country: undefined,
    timeZone: undefined,
    city: undefined,
    harbor: undefined,
    addressPermanent: undefined,
    addressMail: undefined,
    sourceCode: undefined,
    industryCode: undefined,
    priorityCode: undefined,
    starCode: undefined,
    stageCode: undefined,
    statusCode: undefined,
    remark: undefined,
    contacts: []
  }
  localContacts.value = []
  selectedContactIds.value = []
  localContactIdCounter = 0
  formRef.value?.resetFields()
}
</script>

<style scoped>
.form-section {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #000000;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

</style>